package com.xiaoger.aop.aop.aspect;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * 系统日志
 *
 * @author xjx
 * @date 2022/5/9 15:27
 */
@Component
@Aspect
@Slf4j
public class AutoLogAspect {

    /**
     * 注解切入点
     */
    @Pointcut(value = "@annotation(com.xiaoger.aop.aop.aspect.AutoLog)")
    public void logPointCut() {
    }


    @Around("logPointCut()")
    public Object around(ProceedingJoinPoint point) throws Throwable {
        long beginTime = System.currentTimeMillis();
        //执行方法
        Object result = point.proceed();
        //执行时长(毫秒)
        long time = System.currentTimeMillis() - beginTime;

        //保存日志
        saveSysLog(point, time, result);
        log.info("接口执行时长为：{}ms", time);

        return result;
    }

    /**
     * 保存日志
     */
    private void saveSysLog(ProceedingJoinPoint point, long time, Object result) {
        MethodSignature signature = (MethodSignature) point.getSignature();
        Method method = signature.getMethod();
        //获取方法上边的注解
        AutoLog syslog = method.getAnnotation(AutoLog.class);
        if (syslog != null) {
            //获取注解里边相关内容
            String value = syslog.value();
            int operateType = syslog.operateType();
            log.info("注解上边的内容为：value:{},operateType:{}", value, AutoLog.OperateType.find(operateType));
            //可以将收集到的信息保存到数据库....
        }
    }

}
